﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Drawing;
using System.Xml.Linq;

namespace CarInfoBusiness
{
    public class GetCarBrands
    {
        private static GetCarBrands gcb;

        public static GetCarBrands Instance
        {
            get
            {
                if (gcb == null)
                    gcb = new GetCarBrands();
                return gcb;
            }
        }

        private GetCarBrands()
        { }

        private int _MaxBrandsLimit = 9999999;

        public int MaxBrandsLimit
        {
            get { return _MaxBrandsLimit; }
            set { _MaxBrandsLimit = value; }
        }


        public List<CarInfoDBAccess.DBAccess_New.CSBrand> GetBrands(string url)
        {
            List<CarInfoDBAccess.DBAccess_New.CSBrand> list = new List<CarInfoDBAccess.DBAccess_New.CSBrand>();
            XElement brandxml = Common.Instance.GetXml(url);
            if (brandxml == null)
                return null;
            var data = from node in brandxml.Descendants()
                       select node;

            foreach (var t in data)
            {
                if (list.Count == MaxBrandsLimit)
                    break;
                if (t.Name.LocalName == "div")
                {
                    if (t.HasAttributes && t.Attributes("class").Count() == 1)
                        if (t.Attribute("class").Value == "search_top2_5_left")
                        {
                            CarInfoDBAccess.DBAccess_New.CSBrand brand = new CarInfoDBAccess.DBAccess_New.CSBrand();
                           // brand.Id = ++LastBrandId;
                            brand.Name = t.Value;
                            var geturl = from u in t.Descendants()
                                         select u;
                            brand.Url = geturl.Single().Attribute("href").Value;

                            string id = brand.Url.Replace("http://db.chinacars.com/11/db_", "");
                            id = id.Replace(".htm", "");
                            brand.Id = Convert.ToInt32(id);

                            list.Add(brand);
                        }

                }
            }
            return list;
        }
       
    }
}
